package demo2;

import demo1.BinaryTree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class TreeNode {
  int val;
    TreeNode left;
  TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
 public TreeNode createTree() {    //创造一个二叉树
TreeNode node1 = new TreeNode(3);
 TreeNode node2 = new TreeNode(9);
 TreeNode node3 = new TreeNode(20);
  TreeNode node4 = new TreeNode(15);
  TreeNode node5 = new TreeNode(7);
  node1.left = node2 ;
  node1.right = node3 ;
  node3.left = node4 ;
  node3.right = node5 ;

  return  node1 ;
 }
    public List<List<Integer>> levelOrder(TreeNode root) {

        List<List<Integer>> list = new ArrayList<>() ;
        if(root == null) return list ;
        Queue<TreeNode> queue = new LinkedList<>() ;

        queue.offer(root);
        while(!queue.isEmpty() ){
            int size = queue.size() ;
            List<Integer> ret = new ArrayList<>() ;
            while(size != 0){
                TreeNode cur = queue.poll() ;
                ret.add(cur.val) ;
                if(cur.left != null){
                    queue.offer(cur.left) ;
                }
                if(cur.right != null){
                    queue.offer(cur.right) ;
                }
                size -- ;
            }
            list.add(ret) ;
        }


        return list ;


    }
  }
